package com.xc.stock.domain.basic.repository;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import org.springframework.data.jpa.repository.support.JpaEntityInformation;

import com.google.common.cache.CacheBuilder;
import com.rp.spring.jpa.GenericJpaRepository;

public class LocalCacheBean<P, ID extends Serializable> {
	LocalCache<P, ID> localCache;
	
	Function<String, List<P>> cb;
	JpaEntityInformation<P, ID> eif;
	public LocalCacheBean(GenericJpaRepository<P, ID> repo, Function<String, List<P>> cb) {
		this(repo, cb, CacheBuilder.newBuilder().maximumSize(2000000).expireAfterWrite(2 * 60, TimeUnit.SECONDS));
	}
	
	public LocalCacheBean(GenericJpaRepository<P, ID> repo, Function<String, List<P>> cb, CacheBuilder<Object, Object> builder) {
		this.cb = cb;
		this.eif = repo.jpaEntityInformation();
		this.localCache = new LocalCache<>(builder, cb(), val -> id(val));
	}
	
	public Function<String, List<P>> cb() {
		return cb;
	}
	
	public ID id(P p) {
		ID id = eif.getRequiredId(p);
		return id;
	}
	
	public List<P> cacheList() {
		return localCache.cacheList();
	}

	public Map<ID, P> cacheMap() {
		return localCache.cacheMap();
	}

	public P findCacheById(ID id) {
		return localCache.findCacheById(id);
	}
	
	public LocalCache<P, ID> localCache() {
		return localCache;
	}
}
